import fileManage from './fileManage.js'
import myPromise from './myPromise.js'

let fs = fileManage.fs,userDataPath = fileManage.userDataPath;
const removeSavedFile = apFilePath=>{
	return new Promise(resolve=>{
		my.removeSavedFile({
			apFilePath,
			success:res=>{
				console.log('remove success')
				resolve()
			},
			fail:res=>{
				console.log('remove fail')
				resolve()
			}
		})
	})
}
export default (tempFilePath,fileName)=>{
	return new Promise((resolve,reject)=>{
		// #ifdef MP-WEIXIN
		fs.saveFile({
			tempFilePath,
			filePath: `${userDataPath}/${fileName}`,
			success(res) {
				console.log('saveFile-success', res.savedFilePath);
				resolve(res)
			},
			fail(res) {
				console.log('saveFile-fail', res);
				reject()
			}
		})
		// #endif
		// #ifdef MP-ALIPAY
		my.getSavedFileList({
		  success:res=>{
		    console.log('getSavedFileList-success',res)
				var promises = []
				res.fileList.forEach(file=>{
					if(file.apFilePath !== tempFilePath){
						var promise = removeSavedFile(file.apFilePath)
						promises.push(promise)
					}
				})
				if(promises.length > 0){
					Promise.all(myPromise(promises)).then(res=>{
						if(res.length === promises.length){
							my.saveFile({
								apFilePath: tempFilePath,
								success(res) {
									console.log('saveFile-success', res.apFilePath);
									res.savedFilePath = res.apFilePath
									resolve(res)
								},
								fail: res=>{
									console.log('saveFile-fail',res)
									reject()
								}
							});
						}
					})
				}else{
					my.saveFile({
						apFilePath: tempFilePath,
						success(res) {
							console.log('saveFile-success', res.apFilePath);
							res.savedFilePath = res.apFilePath
							resolve(res)
						},
						fail: res=>{
							console.log('saveFile-fail',res)
							reject()
						}
					});
				}
		  },
			fail: res=>{
				console.log('getSavedFileList-fail',res)
				reject()
			}
		});
		// #endif
	})
}